var _RegExpCellPhone = /^(\+[0-9]{2,4}-)?1[0-9]{10}$/;
var _RegExpTelePhone = /^(\+[0-9]{2,4}-)?0[0-9]{2,3}-[0-9]{7,8}$/;
var _RegExpEMail = /^[A-Za-z0-9_]+\@[A-Za-z0-9_]+\.[A-Za-z0-9_]+$/;

_PageSize = parseInt((window.screen.availHeight - 300) / 28);

function toUrlParams(obj) {
	var result = "";
	var flag = false;
	for ( var item in obj) {
		if (flag) {
			result += "&";
		}
		if (obj[item] == null) {
			result += item + "=null";
			flag = true;
		} else if (obj[item] instanceof Number || obj[item] instanceof String
				|| obj[item] instanceof Date) {
			result += item + "=" + obj[item];
			flag = true;
		} else if (obj[item] instanceof Array) {
			var array = obj[item];
			for (var i = 0; i < array.length; i++) {
				if (flag) {
					result += "&";
				}
				result += item + "=" + array[i];
				flag = true;
			}
		} else {
			result += item + "=" + obj[item];
			flag = true;
		}
	}
	return result;
}
function format(date, format) {
	if (!date) {
		return "　- - ";
	}
	if (!format) {
		return date.toString();
	}
	try {
		var y = date.getFullYear(), m = date.getMonth() + 1, d = date.getDate(), h = date
				.getHours(), i = date.getMinutes(), s = date.getSeconds();
		format = format.replace("Y", y);
		format = format.replace("M", m < 10 ? "0" + m : m);
		format = format.replace("D", d < 10 ? "0" + d : d);
		format = format.replace("H", h < 10 ? "0" + h : h);
		format = format.replace("I", i < 10 ? "0" + i : i);
		format = format.replace("S", s < 10 ? "0" + s : s);
		return format;
	} catch (e) {
		return "　- - ";
	}
}
function setField(form, name, val) {
	if (!name || (name instanceof String)) {
		return false;
	}
	return form.find("[name=" + name + "]").val(val);
}
function getField(form, name) {
	if (!name || (name instanceof String)) {
		return null;
	}
	return form.find("#" + name).val()
			|| form.find("[name=" + name + "]").val();
}
function getData(form) {
	var data = {};
	form.find("[name]").each(function(index, item) {
		switch (item.tagName) {
		case "TEXTAREA":
		case "INPUT":
		case "SELECT":
			if (item.value) {
				data[item.name] = item.value;
			}
			break;
		case "IMG":
			data[item.name] = item.src;
			break;
		}
	});
	return data;
}
function setData(form, data) {
	form.find("[name]").each(function(index, item) {
		var name = item.name || $(item).attr("name");
		var value = data[name];
		var display = $(item).attr("display");
		if (display) {
			value = eval(display)[value];
		}
		try {
			if (value != null) {
				switch (item.tagName) {
				case "DIV":
				case "TEXTAREA":
				case "SPAN":
					item.innerHTML = value;
					break;
				case "SELECT":
				case "INPUT":
					item.value = value;
					break;
				case "IMG":
					var indexImg = value.indexOf("http://");
					if(indexImg<0){
						item.src = value;
						//item.src = 'http://www.t10mall.com/images'+value;
					}else{
						item.src = value;
					}
					break;
				}
			}
		} catch (e) {
		}
	});
}
function clearData(form) {
	form.find("[name][type!=hidden]").each(function(index, item) {
		switch (item.tagName) {
		case "TEXTAREA":
		case "INPUT":
			item.value = "";
			break;
		case "IMG":
			item.src = "";
			break;
		}
	});
}
function closeEditer(btn, updateRow, formData) {
	var form = $($(btn).parents(".form").parent().children(".form")[0]);
	form.triggerHandler("close", form);
	layer.close(_editerIndex);
	if (updateRow && window.editingData) {
		this.updateRow(form, formData);
	}
}
function updateRow(form, formData) {
	var newData = formData || getData(form);
	var oldData = editingData;
	for ( var item in oldData) {
		if (newData[item] == undefined || newData[item] == null) {
			newData[item] = oldData[item];
		}
	}
	if (editingIndex !== null && editingIndex !== undefined && newData) {
		$("#dataTable").jqxDataTable("updateRow", editingIndex, newData);
	}
}
function getFirstDayOfLastmonth() {
	var data = getFirstDayOfMonth();
	return new Date(data.getFullYear(), data.getMonth() - 1, 1);
}
function getLastDayOfLastmonth() {
	var data = getFirstDayOfMonth();
	return new Date(data.getFullYear(), data.getMonth(), 0);
}
function getFirstDayOfMonth() {
	var now = new Date();
	return new Date(now.getFullYear(), now.getMonth(), 1);
}
function getNowDay() {
	var now = new Date();
	return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59,
			59);
}
function deleteEditer(btn, close, callback) {
	var form = $($(btn).parents(".form").parent().children(".form")[0]);
	var data = getData(form);
	var url = getField(form, "delete-url");
	var btnValue = btn.value;
	$.ajax({
		url : url,
		data : data,
		async : true,
		success : function(result) {
			if (result.code == 0) {
				layer.msg(result.msg || "Unknow finish message...", {
					offset : "5%"
				});
				if (close != false) {
					closeEditer(btn, true);
				} else {
					btn.value = btnValue;
					btn.disabled = null;
				}
				if (callback && typeof (callback) == "function") {
					callback.apply(form, [ form, result, data, url ]);
				}
			} else {
				layer.msg(result.msg || "Unknow error message...", {
					offset : "5%",
					shift : 6
				});
				btn.value = btnValue;
				btn.disabled = null;
			}
		}
	});
	btn.value = "删除中...";
	btn.disabled = "disabled";
}
function tipErr(ele, msg) {
	var shift = $(".layui-layer-tips").length ? 6 : 0;

	ele.focus();
	ele.blur();

	_TipIndex = layer.tips(msg, ele, {
		tips : [ 1, 'red' ],
		shift : shift,
		time : 4444
	});

	function thisOnFocus() {
		layer.close(_TipIndex);
		$(ele).unbind("focus", thisOnFocus);
	}

	$(ele).bind("focus", thisOnFocus);
}
function submitEditer(btn, close, callback) {
	var form = $($(btn).parents(".form").parent().children(".form")[0]);
	var data = getData(form);
	//测试
	//alert(data);
	var flag = false;
	form.find("[name][allowBlank=false]").each(function() {
		var name = this.name || $(this).attr("name");
		if (data[name] == null || data[name] == "") {
			flag = true;
			name = this.placeholder || $(this).attr("placeholder") || name;
			tipErr(this, "字段 \"" + name + "\"不允许是空值！");
			return false;
		}
		
	});
	if (flag) {
		return false;
	}
	form.find("[name][unallows]").each(function() {
		var name = this.name || $(this).attr("name");
		var unallows = $(this).attr("unallows");
		try {
			unallows = eval("(" + unallows + ")");
		} catch (e) {
		}
		if (!(unallows instanceof Array)) {
			unallows = [ unallows ];
		}
		for (var i = 0; i < unallows.length; i++) {
			if (unallows[i] == data[name]) {
				flag = true;
				name = this.placeholder || $(this).attr("placeholder") || name;

				tipErr(this, "字段\"" + name + "\"不允许是\"" + unallows[i] + "\"");

				return false;
			}
		}
	});
	if (flag) {
		return false;
	}
	form.find("[name][allows]").each(function() {
		var name = this.name || $(this).attr("name");
		var allows = $(this).attr("allows");
		try {
			allows = eval("(" + allows + ")");
		} catch (e) {
		}
		if (!(allows instanceof Array)) {
			allows = [ allows ];
		}
		for (var i = 0; i < allows.length; i++) {
			if (allows[i] instanceof RegExp) {
				if (allows[i].test(data[name])) {
					return true;
				}
			} else if (allows[i] == data[name]) {
				return true;
			}
		}
		flag = true;
		name = this.placeholder || $(this).attr("placeholder") || name;

		tipErr(this, "字段 \"" + name + "\"的格式不正确。");

		return false;
	});
	if (flag) {
		return false;
	}
	var url = getField(form, "submit-url");
	var btnValue = btn.value;
	var formFiles = form.find("input[type=file]");
	var useForm = formFiles.length != 0;
	if (useForm) {
		useForm = false;
		formFiles.each(function() {
			if (this.value != null && this.value != "") {
				useForm = true;
				return false;
			}
		});
	}
	function successCallback(result) {
		if (typeof (result) == "string") {
			eval("result = " + result);
		}
		if (result.code == 0) {
			layer.msg(result.msg || "Unknow finish message...", {
				offset : "5%"
			});
			if (close != false) {
				closeEditer(btn, true, result.data || data);
			} else {
				btn.value = btnValue;
				btn.disabled = null;
			}
			if (callback && typeof (callback) == "function") {
				callback.apply(form, [ form, result, data, url ]);
			}
		} else {
			layer.msg(result.msg || "Unknow error message...", {
				offset : "5%",
				shift : 6
			});
			btn.value = btnValue;
			btn.disabled = null;
		}
	}
	if (window.doSubmit && typeof (window.doSubmit) == "function") {
		if (useForm) {
			var oldData = clone(data);
			if (doSubmit.apply(form, [ form, data, url ]) === false) {
				return false;
			}
			for ( var item in data) {
				if (oldData[item] != data[item]) {
					if (oldData[item] == null) {
						form.append("<input type='hidden' name='" + item
								+ "' value='" + data[item] + "'/>");
					} else {
						form.find("[name=" + item + "]").attr("value",
								data[item]);
					}
				}
			}

		} else {
			if (doSubmit.apply(form, [ form, data, url ]) === false) {
				return false;
			}
		}
	}
	if (useForm) {
		var iframeName = "_InnrtSubmitIframe";
		var iframe = $("iframe[name=_InnrtSubmitIframe]")[0];
		if (!iframe) {
			function loadCallback(event) {
				var responseText = iframe.contentDocument.body.innerText;
				successCallback(responseText);
			}
			iframe = document.createElement("iframe");
			iframe.name = iframeName;
			iframe.style.display = "none";
			document.body.appendChild(iframe);
			if (iframe.attachEvent) {
				iframe.attachEvent("onload", loadCallback);
			} else {
				iframe.addEventListener("load", loadCallback, false);
			}
		}
		form.attr("target", iframeName);
		form.attr("action", url);
		form.submit();
	} else {
		$.ajax({
			url : url,
			type:'post',
			data : data,
			async : true,
			success : successCallback
		});
	}
	btn.value = "正在提交...";
	btn.disabled = "disabled";
}
function map(items, field, newName, deleteOld) {
	for (var i = 0; i < items.length; i++) {
		items[i][newName] = items[i][field];
		if (deleteOld) {
			delete items[i][newName];
		}
	}
}
function clone(obj) {
	if (obj && typeof (obj) == "object" && !(obj instanceof Date)) {
		var newObj = {};
		for ( var item in obj) {
			newObj[item] = clone(obj[item]);
		}
		return newObj;
	}
	return obj;
}
function update(tab, params) {
	var tableSource = tab.jqxDataTable("source");
	if (params) {
		tableSource._source.data = params;
	}
	var newSource = new $.jqx.dataAdapter(tableSource._source);
	tab.jqxDataTable({
		source : newSource
	});
}
function indexOf(array, item) {
	for (var i = 0; i < array.length; i++) {
		if (array[i].id == item.id) {
			return i;
		}
	}
	return -1;
}
function find(items, key, value, children) {
	if (!items || !items.length) {
		return null;
	}
	for (var i = 0; i < items.length; i++) {
		if (!items[i]) {
			continue;
		}
		if (items[i][key] == value) {
			return items[i];
		}
		if (children) {
			var item = find(items[i][children], key, value, children);
			if (item) {
				return item;
			}
		}
	}
	return null;
}
function findIndex(items, key, value) {
	if (!items || !items.length) {
		return -1;
	}
	for (var i = 0; i < items.length; i++) {
		if (items[i][key] == value) {
			return i;
		}
	}
	return -1;
}
function getSelected() {
	var selected = $("#dataTable").jqxDataTable("getSelection")[0];
	var index;
	if (!selected
			|| (index = indexOf($("#dataTable").jqxDataTable("getView"),
					selected)) == -1) {
		layer.msg("请选择一行数据", {
			shift : 6,
			offset : "5%"
		});
		return false;
	}
	return {
		row : selected,
		index : index
	};
}
function focus(element) {
	element.after("<INPUT ID='TEMP'/>");
	$("#TEMP").focus();
	$("#TEMP").remove();
	element.focus();
}
$(function() {
	if (window.no_select === undefined) {
		$("#select").click(function() {
			var data = getData($(this).parents(".toolbox"));
			for ( var item in data) {
				if (!data[item]) {
					data[item] = undefined;
				}
			}
			if (data.address) {
				var args = data.address.split(".");
				data.province = args[0];
				data.city = args[1];
				data.district = args[2];
				delete data.address;
			}
			update($("#dataTable"), data);
		});
	}

	if (window.no_update === undefined) {
		$("#update").click(function() {
			update($("#dataTable"));
		});
	}

	if (window.no_edit === undefined) {
		$("#edit").click(
				function() {
					_windowModel = "edit";
					var selection = $("#dataTable")
							.jqxDataTable("getSelection");
					var record = selection[0];
					if (!record) {
						layer.msg("请选择一行数据", {
							shift : 6,
							offset : "5%"
						});
						return false;
					}
					var index = indexOf(
							$("#dataTable").jqxDataTable("getView"), record);
					if (index == -1) {
						layer.msg("请选择一行数据", {
							shift : 6,
							offset : "5%"
						});
						return false;
					}
					$("#dataTable").trigger("rowDoubleClick", {
						args : {
							row : record,
							index : index,
							type : "edit"
						},
						flag : true
					});
				});
	}
	if (window.no_operate === undefined) {
		$("#delete,[id$=-operate]").click(
				function() {
					var selection = $("#dataTable")
							.jqxDataTable("getSelection");
					if (!selection || !selection.length) {
						layer.msg("请选择至少一行数据", {
							shift : 6,
							offset : "5%",
							time : 9999999
						});
						return false;
					}
					var btn = this;
					var btnValue = btn.value;
					layer.confirm("确定要将它们" + btnValue + "吗？", {
						icon : 3,
						title : "操作提示",
						closeBtn : false,
						skin : "layui-layer-red",
						btn : [ "确定", "取消" ]
					}, function() {
						var deletes = [];
						for (var i = 0; i < selection.length; i++) {
							deletes.push(selection[i].id);
						}
						var submitUrl = getField($(btn).parent(), btn.id
								.replace("-operate", "")
								+ "-url");
						$.ajax({
							url : submitUrl,
							data : toUrlParams({
								ids : deletes
							}),
							async : true,
							success : function(result) {
								if (result.code == 0) {
									layer.msg(result.msg
											|| "Unknow finish message...", {
										offset : "5%"
									});
									update($("#dataTable"));
								} else {
									layer.msg(result.msg
											|| "Unknow error message...", {
										offset : "5%",
										shift : 6
									});
								}
								btn.value = btnValue;
								btn.disabled = null;
							}
						});
						btn.value = "正在提交...";
						btn.disabled = "disabled";
					});
				});
	}
	if (window.no_add === undefined) {
		$("#add").click(function() {
			_windowModel = "add";
			$("#dataTable").jqxDataTable('clearSelection');
			var submitUrl = getField($(this).parent(), "add-url");
			$("#dataTable").trigger("rowDoubleClick", {
				args : {
					row : {
						"submit-url" : submitUrl
					},
					type : "add"
				},
				flag : true
			});
			$("[id$=-editer]").on("close", function() {
				update($("#dataTable"));
			});
		});
	}



	if (window.no_download === undefined) {
		$("#download").click(function() {
			var submitUrl = this.href;
			var data = getData($(this).parents(".toolbox"));
			for ( var item in data) {
				if (!data[item]) {
					data[item] = undefined;
				}
			}
			if (data.address) {
				var args = data.address.split(".");
				data.province = args[0];
				data.city = args[1];
				data.district = args[2];
				delete data.address;
			}
			window.location = submitUrl + "?" + toUrlParams(data);
			return false;
		});
	}

	$(".input-group-btn>ul>li>a").live("click", function() {
		var dis = $(this).parents(".input-group-btn");
		dis.find("button").html(this.innerHTML + " <span class=\"caret\">");
		dis.find("input").val(this.id);
	});

	$("notnull").live("mouseenter", function() {
		this.title = "这个字段是必须输入的。";
	});

	$(".cell-tips").live("mouseenter", function() {
		_TipIndex = layer.tips(this.innerHTML, this, {
			tips : [ 1, '#0FA6D8' ],
			time : 8888
		});
	});

	$(".cell-tips").live("mouseleave", function() {
		layer.close(_TipIndex);
	});

	$(".bootstrap-tagsinput input").live("keypress", function(event) {
		if (event.keyCode == 13) {
			focus($(this));
		}
	});

	$(".form-control.tags-input").live("click", function() {
		focus($(this).find(".bootstrap-tagsinput input"));
	});
	
});